<template>
  <view class="content">
    <image class="logo" src="/static/logo.png"></image>
    <view>
      <text class="title">{{ title }}</text>
      <button @tap="getUserProfile">按钮点击授权登录</button>
<!--      <button-->
<!--        open-type="getPhoneNumber"-->
<!--        type="primary"-->
<!--        class="bottom"-->
<!--        @getphonenumber="getPhoneNumber"-->
<!--      >-->
<!--        授权手机号-->
<!--      </button>-->
    </view>
    <view> 手机号为:{{ phoneNumber }} </view>
    <button type="primary" size="mini" @tap="pushMesage">推送消息</button>
  </view>
</template>

<script>
// import { getLogin } from "@/api/login/login";


const app = getApp();
export default {
  data() {
    return {
      title: "Hello",
      encryptedData: "",
      iv: "",
      phoneNumber: 0,
    };
  },
  onLoad() {
    // uni.showLoading({
    //   title: "加载中...",
    // });
  },
  onShow(){
    // this.pushMesage()
  },
  methods: {
    pushMesage(){
      console.log('点击了')
      //弹窗授权消息推送 //新推粉丝
      app.globalData.pushMesage()
      //直接请求推送
      // app.globalData.sendMsg();
    },
    login() {
      uni.navigateTo({
        url: `/pages/empower/mp-weixin`,
      });
    },

    goLogin() {
      const app = this;
      //判断缓存中是否有用户数据，没有则获取
      if (!uni.getStorageSync("encryptedData")) {
        uni.getUserProfile({
          desc: "获取您的昵称、头像、地区及性別",
          success: async (infoRes) => {
            console.log(infoRes, "获取的用户信息");
            if (infoRes.errMsg === "getUserProfile:ok") {
              await app.getCode();
              // 获取到的当前数据存入缓存
              // uni.setStorageSync("encryptedData", infoRes.encryptedData);
              // uni.setStorageSync("iv", infoRes.iv);
              // uni.setStorageSync("rawData", infoRes.rawData);
              // uni.setStorageSync("signature", infoRes.signature);
              // uni.setStorageSync("securityStatus", 1);
              // 选择版本
              // uni.navigateTo({
              //   url: "/platforms/mp-weixin/register/registerVersion",
              // });
            } else {
              uni.showToast({
                title: "获取失败",
                icon: "error",
              });
            }
          },
          fail: (err) => {
            console.log("userInfo-err", JSON.stringify(err));
          },
        });
      } else {
        console.log("缓存中有数据");
        // uni.navigateTo({
        //   url: "/platforms/mp-weixin/register/registerVersion",
        // });
      }
    },



    getCode() {
      const than = this;
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: (res) => {
            console.log(res, "res code");
            resolve(res.code);
          },
          fail: reject,
        });
      });
    },

    trimAll(ele) {
      if (typeof ele === "string") {
        return ele.split(/[\t\r\f\n\s]*/g).join("");
      } else {
        console.error(
          `${typeof ele} is not the expected type, but the string type is expected`
        );
      }
    },

    // 获取微信用户信息(新版)
    getUserProfile() {
		return
      //获取用户信息 包含appid
      // const appid = uni.getAccountInfoSync();
      // console.log(appid, "appid");
      // app.globalData.getUserProfile();
      // return
      // const app = this;
      //检查登录态是否过期
      uni.checkSession({
        provider: "weixin",
        success: function (loginRes) {
          console.log("checkSession成功", loginRes);
        },
        fail: function (loginRes) {
          console.log("checkSession失败", loginRes);
        },
      });

      wx.canIUse("getUserProfile") &&
        wx.getUserProfile({
          lang: "zh_CN",
          desc: "获取用户相关信息",
          async success(res) {
            console.log("用户同意了授权");
            console.log("用户信息:", res);
            const { encryptedData, iv } = res;
            const {
              gender,
              avatarUrl,
              city,
              country,
              language,
              nickName,
              province,
            } = res.userInfo;
            uni.setStorageSync("MyUserInfo", res.userInfo);
            app.encryptedData = encryptedData;
            app.iv = iv;
            const code = await app.globalData.getCode();
            const data = {
              code,
              wxEncryptInfo: {
                encryptedData: app.globalData.trimAll(encryptedData),
                iv,
              },
              memberInfo: {
                avatarUrl: avatarUrl || "",
                city: city || "",
                country: country || "",
                gender: gender || "",
                language: language || "",
                nickName: nickName || "",
                province: province || "",
              },
            };
            const logoData = await getLogin(data);
            console.log(logoData, "登录授权接口");
            if (logoData.code === 0) {
               // 获取到的当前数据存入缓存
              const {wxToken,openId,userInfo}=logoData.data
              uni.setStorageSync("token", wxToken);
              uni.setStorageSync("openId", openId);
              uni.setStorageSync("userInfoServer", userInfo);
              uni.setStorageSync("userId", userInfo.userId);
              uni.showToast({
                title: "登录成功",
                icon: "success",
                duration: 2000,
              });
            }
            // app.openIdFn(code);
            // 授权成功事件
            // app.onAuthSuccess(userInfo);
          },
          fail() {
            console.log("用户拒绝了授权");
          },
        });
    },

  },
};
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin: 200rpx auto 50rpx auto;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>
